package com.mqtt.ctwingmqtt.controller;


import com.mqtt.ctwingmqtt.domain.ResponseResult;
import com.mqtt.ctwingmqtt.domain.dto.Login;
import com.mqtt.ctwingmqtt.domain.dto.UserDTO;
import com.mqtt.ctwingmqtt.security.utils.JwtUtil;
import com.mqtt.ctwingmqtt.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/auth")
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;
    /**
     * 登录接口
     * @param login
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "登录")
    public ResponseResult<Map<String, Object>> login(@RequestBody Login login){
        //校验用户名密码
        if (authenticate(login.getUsername(), login.getPassword())){
            //获取角色
            //String role = getRole(login.getUsername());
            //获取角色id
            //Integer roleId = userService.getRoleIdByRoleName(role);
            //获取权限，根据角色id查询中间表的权限id
            //List<String> permissions = userService.getPermissionsByRoleId(roleId);
            // 手动创建认证对象
            UsernamePasswordAuthenticationToken authentication =
                    new UsernamePasswordAuthenticationToken(
                            login.getUsername(),
                            null
                            //Collections.singletonList(new SimpleGrantedAuthority(role))
                    );
            // 将认证信息存入 SecurityContext
            SecurityContextHolder.getContext().setAuthentication(authentication);
            //生成token令牌，传入用户名和角色信息，通过tokenutils生成包含role的token，后续方便secuity的角色验证
            String token = jwtUtil.createToken(login.getUsername());
            // 封装数据到 Map
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            //data.put("role:", role);
            //data.put("permissions:", permissions);
            return ResponseResult.success(data);
        } else {
            // 返回 401 Unauthorized 状态码
            return ResponseResult.error("用户名或密码错误");
        }
    }

    /**
     * 注册接口
     * @param user
     * @return
     */
    @PostMapping("/registered")
    @ApiOperation(value = "注册")
    public ResponseResult<String> registered(@RequestBody UserDTO user){
        //拿到用户信息插入数据库
        Boolean b = userService.insect(user);
        if (!b){
            return ResponseResult.error("注册失败，用户已存在");
        }
        return ResponseResult.success("注册成功",user.getUsername());
    }

    /**
     * 根据用户名获取角色
     * @param username
     * @return
     */
    private String getRole(String username) {
        return userService.getRole(username);
    }
    /**
     * 验证用户名密码
     * @param username
     * @param password
     * @return
     */
    private boolean authenticate(String username, String password) {
        return userService.getPassword(username).equals(password);

    }

}
